﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

class CConnectionManager
{
    public struct SThreadConnection
    {
        public int m_nThreadId;
        public SqlCommand m_SqlComm;

        public SThreadConnection(int nThreadId, SqlCommand SqlComm)
        {
            m_nThreadId = nThreadId;
            m_SqlComm = SqlComm;
        }
    }

    private String m_sConnString = "Data Source =10.5.5.234; Initial Catalog = FlightDB; USER ID= admin; PASSWORD=123";
    private List<SThreadConnection> m_ThreadConnList;

    public CConnectionManager()
    {
        m_ThreadConnList = new List<SThreadConnection>();
    }

    public SqlCommand GetSqlCommand(int nThreadId)
    {
        lock (this)
        {
            foreach (SThreadConnection ThreadConn in m_ThreadConnList)
            {
                if (ThreadConn.m_nThreadId == nThreadId)
                    return ThreadConn.m_SqlComm;
            }

            SqlCommand SqlComm = new SqlCommand("", new SqlConnection(m_sConnString));
            SqlComm.Connection.Open();
            m_ThreadConnList.Add(new SThreadConnection(nThreadId, SqlComm));

            return SqlComm;
        }
    }

    public void CloseConnections()
    {
        foreach (SThreadConnection ThreadConn in m_ThreadConnList)
        {
            ThreadConn.m_SqlComm.Connection.Close();
        }

        m_ThreadConnList.Clear();
    }
}

